#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h> 
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>
#include <stdint.h>

#include "server.h"

void printTimestamp(char *prefix)
{
    char buf[80];
    time_t t;
    struct tm *tmp;

    t = time(NULL);
    tmp = localtime(&t);

    strftime(buf, 80, "%a, %d %b %Y %T %z", tmp);
    printf("%s: %s\n", prefix, buf);
}

int main(int argc, char **argv) {

    int sockfd;
    int port_number;
    ssize_t n;
    
    struct sockaddr_in serveraddr;
    struct hostent *server;
    char *hostname;

    int cmd = 10;
    struct directions d_bswp;
    struct directions d;

    /* check command line arguments */
    if (argc != 3) {
       fprintf(stderr,"usage: %s <hostname> <port>\n", argv[0]);
       exit(0);
    }
    hostname = argv[1];
    port_number = atoi(argv[2]);

    /* socket: create the socket */
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0) {
        perror("ERROR opening socket");
    }

    /* gethostbyname: get the server's DNS entry */
    server = gethostbyname(hostname);
    if (server == NULL) {
        fprintf(stderr,"ERROR, no such host as %s\n", hostname);
        exit(0);
    }

    /* build the server's Internet address */
    bzero((char *) &serveraddr, sizeof(serveraddr));
    serveraddr.sin_family = AF_INET;
    bcopy((char *)server->h_addr, 
	  (char *)&serveraddr.sin_addr.s_addr, server->h_length);
    serveraddr.sin_port = htons(port_number);

    /* connect: create a connection with the server */
    if (connect(sockfd, (sockaddr*) &serveraddr, sizeof(serveraddr)) < 0) {
        perror("ERROR connecting");
    }

    while (1) {
        /* send the message line to the server */
        n = write(sockfd, &cmd, sizeof(cmd));
        if (n != sizeof(cmd)) {
            perror("ERROR writing to socket");
        }
        
        n = read(sockfd, &d_bswp, sizeof(d_bswp));
        if (n < 0)  {
            perror("ERROR reading from socket");
        } else {
            d.vert_angle = htonl(d_bswp.vert_angle);
            d.horiz_angle = htonl(d_bswp.horiz_angle);
            d.dist = htonl(d_bswp.dist);
            d.status = htonl(d_bswp.status);
            
            printTimestamp((char *) "Got the following info from server");
            if (d.status == 0) {
                printf("vert_angle = %d\n", d.vert_angle);
                printf("horiz_angle = %d\n", d.horiz_angle);
                printf("distance = %d\n", d.dist);
            } else {
                printf("status = %d\n", d.status);
            }
            printf("\n");
        }
        sleep(1);
    }
    
    close(sockfd);
    return 0;
}
